<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <!-- <crudOperation :permission="permission" /> -->
      <el-upload
        class="filter-item"
        :before-upload="beforeUploadFile"
        :on-change="fileChange"
        :on-success="handleSuccess"
        :on-error="handleError"
        :on-preview="handlePreview"
        multiple
        :data="dataParams"
        accept=".xlsx"
        :file-list="fileList"
        :headers="headers()"
        :action="UploadUrl()"
      >
        <el-button
          class="filter-item"
          type="primary"
          icon="el-icon-upload"
          :loading="uploadLoading"
          size="mini"
          :disabled="crud.selections.length !== 1"
          @click="doUpload(crud.selections[0].deptId)"
        >
          导入
        </el-button>
      </el-upload>
      <el-button
        size="mini"
        class="filter-item"
        type="warning"
        icon="el-icon-download"
        :loading="downloadLoading"
        :disabled="crud.selections.length !== 1"
        @click="doExport(crud.selections[0].deptId)"
      >导出
      </el-button>
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="500px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="110px">
          <el-form-item v-if="crud.status.add ===0" label="编号" prop="id">
            <el-input v-model="form.id" style="width: 370px;" disabled />
          </el-form-item>
          <el-form-item label="渠道类型" prop="deptName">
            <el-select v-model="form.deptName" filterable placeholder="请选择" style="width: 370px;" disabled>
              <el-option
                v-for="item in system"
                :key="item.id"
                :label="item.label"
                :value="item.label"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="比例阈值(%)" prop="ratio">
            <el-input-number v-model="form.ratio" style="width: 370px;" :controls="false" :min="1" />
          </el-form-item>
          <!-- <el-form-item label="渠道状态" prop="integralRuleStatus">
            <el-radio v-for="item in dict.integral_rule_status" :key="item.id" v-model="form.integralRuleStatus" :label="item.value">{{ item.label }}</el-radio>
          </el-form-item> -->
          <el-form-item label="备注">
            <el-input v-model="form.remark" style="width: 370px;" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label=" 编号" />
        <el-table-column prop="deptName" label="渠道类型" align="center" />
        <el-table-column prop="ratio" label="比例阈值(%)" align="center" />
        <!-- <el-table-column prop="integralRuleStatus" label="渠道状态" align="center">
          <template slot-scope="scope">
            {{ dict.label.integral_rule_status[scope.row.integralRuleStatus] }}
          </template>
        </el-table-column> -->
        <el-table-column prop="updateTime" label="更新时间" align="center">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.updateTime) }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="remark" label="备注" align="center" /> -->
        <!-- <el-table-column v-permission="['admin']" label="操作" width="180px" align="center"> -->
        <!-- <template slot-scope="scope"> -->
        <!-- <el-button
              size="mini"
              class="filter-item"
              type="warning"
              icon="el-icon-download"
              :loading="downloadLoading"
              @click="doExport(scope.row.deptId)"
            >导出</el-button> -->
        <!-- <el-button
              slot="reference"
              v-permission="['admin']"
              class="filter-item"
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="toDelete(scope.row)"
            >
              {{ scope.row.integralRuleStatus===0 ? '禁用': '启用' }}
            </el-button> -->
        <!-- </template> -->
        <!-- </el-table-column> -->
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import crudIntegralRatio from '@/api/integralRatio'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import pagination from '@crud/Pagination'
import crudDept from '@/api/system/dept'
import { download } from '@/api/data'
import { downloadFile } from '@/utils/index'
import { getToken } from '@/utils/auth'

const defaultForm = { id: null, deptName: null, ratio: null, integralRuleStatus: '1', updateTime: null, remark: null }
export default {
  name: 'IntegralRatio',
  components: { pagination },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['channel_type', 'integral_rule_status'],
  cruds() {
    return CRUD({ title: 'integralRatio', url: 'api/integralRatio', idField: 'id',
      sort: 'id,desc', crudMethod: { ...crudIntegralRatio }
    })
  },
  data() {
    return {
      uploadUrl: '',
      downloadLoading: false,
      uploadLoading: false,
      dataParams: null,
      fileList: [],
      system: '',
      permission: {
        add: ['admin', 'integralRatio:add'],
        edit: ['admin', 'integralRatio:edit'],
        del: ['admin', 'integralRatio:del']
      },
      rules: {
        deptName: [
          { required: true, message: '渠道类型不能为空', trigger: 'blur' }
        ],
        ratio: [
          { required: true, message: '比例阈值不能为空', trigger: 'blur' }
        ],
        integralRuleStatus: [
          { required: true, message: '是否有效不能为空', trigger: 'blur' }
        ]
      },
      queryTypeOptions: [
        { key: 'channelType', display_name: '渠道类型' }
      ]
    }
  },
  mounted() {
    this.systemGet()
  },
  methods: {
    toDelete(val) {
      val.integralRuleStatus = '1'
      crudIntegralRatio.edit(val).then(res => {
        this.$message.warning(res)
      })
    },
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    [CRUD.HOOK.beforeToEdit](a, b) {
      b.deptName = b.deptName + ''
      b.integralRuleStatus = b.integralRuleStatus + ''
      return true
    },

    systemGet() {
      // 获取系统下拉框数据
      let pro = {}
      const that = this
      setTimeout(() => {
        crudDept.getDepts({ pidIsNull: true }).then(res => {
          pro = res
          that.system = res.content
        })
      }, 100)
    },
    // 文件状态改变时的钩子
    fileChange(file, fileList) {
      // console.log(file.raw)
      this.fileList.push(file.raw)
      // console.log(this.fileList)
    },
    // 上传文件之前的钩子, 参数为上传的文件,若返回 false 或者返回 Promise 且被 reject，则停止上传
    beforeUploadFile(file) {
      // console.log('before upload')
      // console.log(file)
      this.uploadLoading = true
      const extension = file.name.substring(file.name.lastIndexOf('.') + 1)
      const size = file.size / 1024 / 1024
      if (extension !== 'xlsx') {
        this.$message.warning('只能上传后缀是.xlsx的文件')
      }
      if (size > 10) {
        this.$message.warning('文件大小不得超过10M')
      }
    },
    UploadUrl: function() {
      return process.env.VUE_APP_BASE_API + '/api/integralRatio/importData'
    },
    headers: function() {
      if (getToken()) {
        return { 'Authorization': getToken() } // 让每个请求携带自定义token 请根据实际情况自行修改
      }
    },
    // 文件上传成功时的钩子
    handleSuccess(res, file, fileList) {
      this.uploadLoading = false
      this.$alert('文件上传成功', '提示', {
        confirmButtonText: '确定',
        callback: action => {
          // 刷新数据
          this.crud.toQuery()
        }
      })
    },
    handlePreview(file, fileList) {

    },
    // 文件上传失败时的钩子
    handleError(err, file, fileList) {
      this.uploadLoading = false
      if (err instanceof Error) {
        const error = JSON.parse(err.message)
        this.$message.error(error.message)
      }
    },
    doUpload(value) {
      this.dataParams = { 'deptId': value }
    },
    doExport(value) {
      this.downloadLoading = true
      const params = {
        'deptId': value
      }
      download('/api/integralRatio' + '/download', params).then(result => {
        downloadFile(result, '比例阈值' + '数据', 'xlsx')
        this.downloadLoading = false
      }).catch(() => {
        this.downloadLoading = false
      })
    }
  }
}
</script>

<style scoped lang="scss">
  .head-container {

   .filter-item {
        margin: 10px 0px ;
        vertical-align: center;
    }

    ::v-deep .el-input-number.is-without-controls .el-input__inner {
      text-align: left;
    }

  }

  ::v-deep .el-upload-list .el-upload-list--text {
    display: none !important;
  }

</style>
